<template>
  <div class="app-container">
    <el-row :gutter="20" class="full-height clear-margin">
      <!--部门数据-->
      <el-col :span="4" :xs="24" class="full-height clear-padding" style="border-right: 1px solid #ddd">
        <div class="head-container" style="border-bottom: 1px solid #ddd">
          <el-input v-model="deptName"
                    placeholder="请输入部门名称"
                    clearable
                    size="small"
                    prefix-icon="el-icon-search"/>
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions"
                   :props="defaultProps"
                   node-key="deptCode"
                   highlight-current
                   :expand-on-click-node="false"
                   :filter-node-method="filterNode"
                   ref="tree"
                   default-expand-all
                   @node-click="handleNodeClick"/>
        </div>
      </el-col>
      <!--角色数据-->
      <el-col :span="20" :xs="24" class="clear-padding">
        <div class="head-container flex-center" style="border-bottom: 1px solid #ddd;">
          <div>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div style="text-align: right">
            <el-button type="primary"
                       plain
                       size="small"
                       v-has-permi="['system:role:insert']"
                       @click="handleAdd">新增角色
            </el-button>
            <el-button type="danger"
                       plain
                       size="small"
                       v-has-permi="['system:role:delete']"
                       :disabled="multiple"
                       @click="handleDelete">删除角色
            </el-button>
          </div>
        </div>

        <div class="body-container">
          <el-form :model="queryParams"
                   ref="queryForm"
                   class="queryForm"
                   :inline="true">
            <el-form-item label="角色名称：" prop="roleName">
              <el-input v-model="queryParams.roleName"
                        placeholder="请输入角色名称"
                        clearable
                        size="small"
                        @input="handleQuery"/>
            </el-form-item>
            <el-form-item label="状态：" prop="status">
              <Select v-model="queryParams.status"
                      size="small"
                      placeholder="请选择角色状态"
                      :options="statusOptions"
                      @change="selectQuery"/>
            </el-form-item>
          </el-form>

          <el-table v-loading="loading"
                    :data="roleList"
                    border
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center"/>
            <el-table-column label="角色名称"
                             prop="roleName"
                             width="150"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="权限字符"
                             prop="roleType"
                             width="150"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="归属部门"
                             width="150"
                             prop="dept.deptName"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="显示顺序"
                             width="100"
                             prop="order"/>
            <el-table-column label="状态"
                             width="100"
                             :formatter="row => descriptionDictDataStatus(row.status, statusOptions)"/>
            <el-table-column label="备注"
                             width="250"
                             prop="remark"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="创建时间"
                             width="200"
                             :formatter="row => dateFormatter(row, 'createTime')"
                             prop="createTime"/>
            <el-table-column label="操作">
              <template slot-scope="scope" v-if="scope.row.roleType !== 'admin'">
                <el-button size="small"
                           type="primary"
                           v-has-permi="['system:role:update']"
                           plain
                           @click="handleUpdate(scope.row)">编辑
                </el-button>
                <el-button size="small"
                           type="success"
                           v-has-permi="['system:role:detail']"
                           plain
                           @click="authConfig(scope.row)">权限设置
                </el-button>
                <el-button size="small"
                           type="danger"
                           v-has-permi="['system:role:delete']"
                           plain
                           @click="handleDelete(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0"
                      :total="total"
                      :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize"
                      @pagination="getList"/>
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title"
               :visible.sync="open"
               width="500px"
               :close-on-click-modal="false"
               append-to-body>
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="110px">
        <el-form-item label="角色名称："
                      prop="roleName">
          <el-input v-model="form.roleName"
                    placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="归属部门：" prop="dept">
          <treeselect v-model="form.dept"
                      :options="deptOptions"
                      :normalizer="normalizer"
                      :show-count="true"
                      placeholder="请选择归属部门"/>
        </el-form-item>
        <el-form-item prop="roleType">
          <span slot="label">
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            权限字符：
          </span>
          <el-input v-model="form.roleType" placeholder="请输入权限字符"/>
        </el-form-item>
        <el-form-item label="角色顺序：" prop="order">
          <el-input-number v-model="form.order" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm">确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog :title="permConfigTitle"
               width="600px"
               :close-on-click-modal="false"
               :visible.sync="permissionConfigShow">

      <el-tree :data="menuOptions"
               :props="menuProps"
               node-key="_id"
               :check-strictly="checkStrictly"
               show-checkbox
               style="height: 500px; overflow: auto"
               ref="menuTree"
               check-on-click-node
               default-expand-all/>

      <div slot="footer">
        <el-button type="primary"
                   v-has-permi="['system:role:update']"
                   @click="handlePermSure">确 认
        </el-button>
        <el-button @click="permissionConfigShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Treeselect from "@riophae/vue-treeselect"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css"
  import Select from '@/components/form/Select'
  import { listRole, getRole, delRole, addRole, updateRole } from "@/api/system/role"
  import { listMenu } from "@/api/system/menu"
  import { treeDept } from "@/api/system/dept"

  export default {
    name: "Role",
    components: {Treeselect, Select},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 角色表格数据
        roleList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态数据字典
        statusOptions: [],
        // 菜单列表
        menuOptions: [],
        // 菜单选项配置
        menuProps: {
          label: 'title',
          children: 'children'
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          status: undefined,
          roleName: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          roleName: [
            {required: true, message: "角色名称不能为空", trigger: "blur"}
          ],
          roleType: [
            {required: true, message: "权限字符不能为空", trigger: "blur"}
          ],
          order: [
            {required: true, message: "角色顺序不能为空", trigger: "blur"}
          ]
        },
        // 权限设置对话框
        permissionConfigShow: false,
        // 权限设置对话框标题
        permConfigTitle: '',
        // 当前角色信息
        currentRole: {},
        // 父子节点是否关联
        checkStrictly: false,
        // 部门树选项
        deptOptions: [],
        // 左侧部门树默认配置
        defaultProps: {
          children: "children",
          label: "deptName"
        },
        // 部门名称
        deptName: '',
        // 当前部门节点
        currentDept: {}
      }
    },
    created() {
      this.getList()
      this.getMenuList()
      this.getTreeSelect()
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data
      })
    },
    methods: {
      /** 查询菜单列表 */
      getMenuList() {
        listMenu().then(async res => {
          this.menuOptions = await this.handleTree(res.data, "menuCode", "parentCode")
        })
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node._id,
          label: '[' + node.deptCode + '] ' + node.deptName,
          children: node.children
        }
      },
      /** 查询部门下拉树结构 */
      getTreeSelect() {
        treeDept().then(response => {
          this.deptOptions = this.handleTree(response.data, 'deptCode', 'parentCode')
        })
      },
      /** 筛选节点 */
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      /** 节点单击事件 */
      handleNodeClick(data) {
        this.queryParams.deptCode = data.deptCode
        this.currentDept = data
        this.getList()
      },
      /** 下拉框选择 */
      selectQuery(val) {
        if (val) this.queryParams.status = val
        else delete this.queryParams.status
        this.getList()
      },
      /** 查询角色列表 */
      getList() {
        this.loading = true
        listRole(this.queryParams).then(response => {
          this.roleList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([])
        }
        this.form = {
          roleName: undefined,
          roleType: undefined,
          dept: undefined,
          order: 0,
          status: "1",
          remark: undefined
        }
        this.resetForm("form")
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.roleType)
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加角色"
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const roleType = row.roleType || this.ids
        getRole(roleType).then(response => {
          this.form = response.data
          this.open = true
          this.title = "修改角色"
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form._id != undefined) {
              updateRole(this.form).then(response => {
                this.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addRole(this.form).then(response => {
                this.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const roleType = row.roleType ? [row.roleType] : this.ids
        this.$confirm('是否确认删除角色编号为"' + roleType + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delRole(roleType)
        }).then(() => {
          this.getList()
          this.msgSuccess("删除成功")
        }).catch(() => {
        })
      },
      /** 权限设置 */
      authConfig(row) {
        this.permissionConfigShow = true
        this.permConfigTitle = row.roleName + '权限设置'
        const {roleType} = row
        this.checkStrictly = true
        getRole(roleType).then(res => {
          this.currentRole = res.data
        }).then(() => {
          this.$refs.menuTree.setCheckedKeys(this.currentRole.permissions)
          this.checkStrictly = false
        })
      },
      /** 勾选所有子节点权限 */
      checkAllNodes(data) {
        console.log(data)
      },
      /** 权限设置对话框确认 */
      handlePermSure() {
        const permissions = this.$refs.menuTree.getCheckedKeys().concat(this.$refs.menuTree.getHalfCheckedKeys())
        this.currentRole.permissions = permissions
        updateRole(this.currentRole).then(() => {
          this.msgSuccess('保存成功')
          this.permissionConfigShow = false
        })
      }
    }
  }
</script>

<style lang="scss">
  .queryForm {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
</style>
